/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import domain.Bankaccount;
import domain.Salary;
import domain.Wcontract;
import java.sql.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

/**
 *
 * @author Alberto
 */
public class SalaryDao {

    EntityManager em;
    EntityTransaction tx;

    public SalaryDao() {
        em = SingletonDao.getInstance().getEntityManager();
        tx = SingletonDao.getTx();
    }

    public Salary getSalary(Integer idSalary){
        Salary m = (Salary) em.createNativeQuery("select * from salary as s where s.idSalary='" + idSalary + "'", Salary.class).getSingleResult();
        return m;
    }

    public void saveSalary(Salary m) {
        tx.begin();
        em.persist(m);
        tx.commit();
    }

    public void removeSalary(Salary m) {
        tx.begin();
        em.remove(m);
        tx.commit();
    }

    public List<Salary> getListSalary(Bankaccount b){
        List<Salary> list = em.createNativeQuery("select * from salary as s where s.bankFK='"+b.getIdBank()+"'", Salary.class).getResultList();
        return list;
    }

    public Salary getSalaryDate(Wcontract wc){
        Salary s = null;
        Date date = new Date(new java.util.Date().getTime());
        int month = date.getMonth()+1;
        int year = date.getYear()+1900;
        List list = em.createNativeQuery("select * from salary as s, bankaccount as b where s.wContractFK='"+wc.getIdWcontract()+"' and b.idBank=s.bankFK and s.dateIncome > '"+year+"-"+month+"-01'", Salary.class).getResultList();
        if(!list.isEmpty()){
            s = (Salary) list.get(0);
        }
        return s;
    }

}
